import type { PageType } from '../../../../lib/page_handler/type'
import type {
  BackgroundImageConfig,
  CustomElementStyleIdValueType,
} from '../../../../types/interfaces'
import { PageHandler } from '../../../../lib/page_handler'
import { UNDEFINED_PAGE_TYPE } from '../../../../lib/page_handler/type'
import { createStandardStyleTag } from '../../../../lib/style_injector'
import { ToolKit } from '../../../../lib/utils/toolkit'
import {
  AppStyleCollections,
  BODY_SELECTOR,
  HOSTNAME,
  logger,
  PlatformConfigs,
  SettingsStyleId,
} from '../../../../types/constants'
import {
  StyleInjectPosition,
  SYMBOLS,
} from '../../../../types/interfaces'

/**
 * 背景应用服务
 */
export class BackgroundImageService {
  readonly name: string = 'BackgroundImageService'
  readonly config: Partial<BackgroundImageConfig> = PlatformConfigs[HOSTNAME]?.global?.defaults?.backgroundImage ?? {}
  private currentUrl: string | null = null
  readonly WALLPAPER_ID: string = AppStyleCollections.Wallpaper.CONTAINER
  readonly STYLE_ID: CustomElementStyleIdValueType = SettingsStyleId.Wallpaper
  private forceCompleted: boolean = false

  get pageType(): PageType {
    return PageHandler.getCurrentPageType()
  }

  createWallpaperElement(): void {
    if (document.getElementById(this.WALLPAPER_ID))
      return

    const wallpaper = document.createElement('div')
    wallpaper.id = this.WALLPAPER_ID
    wallpaper.classList = 'wallpaper'
    wallpaper.innerHTML = `
      <div class="${AppStyleCollections.Wallpaper.MASK}"></div>
    `
    // 标记为项目模块
    ToolKit.browser.platform.markProjectElement($(wallpaper))

    // 插入到 body 的最前面
    document.body.insertAdjacentElement('afterbegin', wallpaper)
  }

  /**
   * 获取选择器
   */
  getSelector(): string {
    if (typeof this.config.selector === 'function') {
      return this.config.selector()
    }
    else {
      return this.config.selector || ''
    }
  }

  /**
   * 应用背景到指定平台
   * @param url 背景 URL
   */
  apply(url: string): void {
    if (!this.config.enabled) {
      logger.warn(`[${this.name}] 背景图片设置已禁用`)
      return
    }

    if (this.pageType === UNDEFINED_PAGE_TYPE) {
      logger.warn(`[${this.name}] 未知页面类型，跳过背景图片设置`)
      return
    }

    this.currentUrl = url

    try {
      if (this.config.wallpaper?.enabled) {
        this.applyToWallpaper()
      }
      else {
        this.applyToSelector()
      }

      if (this.forceCompleted)
        return

      logger.info(`[${this.name}] ${SYMBOLS.STATUS.SUCCESS} 背景图片设置成功`)
    }
    catch (error: any) {
      logger.error(`[${this.name}] ${SYMBOLS.STATUS.ERROR} 背景图片设置失败:`, error)
    }
  }

  /**
   * 方式一：设置背景图片（更新容器）
   */
  private applyToSelector(): void {
    const $target = $(this.getSelector())

    if (!$target.length) {
      logger.warn(`[${this.name}] 未找到目标元素: ${this.getSelector()}，跳过背景图片设置`)
      return
    }

    if (!this.checkUrl())
      return

    const fullStyle = `${this.config.cssProperty}: url("${this.currentUrl}"); ${this.config.extraStyles || ''}`

    $target.attr('style', fullStyle)
  }

  /**
   * 方式二：设置背景图片（更新壁纸图层）
   */
  applyToWallpaper(): void {
    this.createWallpaperElement()
    this.createStyleTag()

    const selector = `#${this.WALLPAPER_ID}.wallpaper`
    const $wallpaper = $(selector)

    if (!$wallpaper.length) {
      logger.warn(`[${this.name}] 未找到壁纸元素: ${selector}，跳过背景图片设置`)
    }

    if (!this.checkUrl())
      return

    $wallpaper.css({
      'z-index': this.config.wallpaper?.zIndex ?? -1,
      'background-image': `url(${this.currentUrl})`,
      'background-size': 'cover',
      'background-position': 'center',
      'background-attachment': 'fixed',
    })
  }

  checkUrl(): boolean {
    if (this.currentUrl)
      return true

    this.forceCompleted = true

    logger.warn(`[${this.name}] 背景图片 URL 为空，跳过背景图片设置`)
    return false
  }

  /**
   * 重置背景
   */
  private resetSelector(): void {
    document.querySelectorAll(this.getSelector()).forEach((el) => {
      el.removeAttribute('style')
    })
  }

  /**
   * 重置背景
   */
  private resetWallpaper(): void {
    const wallpaper = document.getElementById(this.WALLPAPER_ID)
    if (wallpaper) {
      wallpaper.style.backgroundImage = ''
    }
  }

  /**
   * 重置
   */
  reset(): void {
    if (this.config.wallpaper?.enabled) {
      this.resetWallpaper()
    }
    else {
      this.resetSelector()
    }
    this.currentUrl = null
  }

  createStyleTag(): void {
    createStandardStyleTag(this.STYLE_ID, this.styles(), { allowEmpty: true, position: StyleInjectPosition.First })
  }

  destroy(): void {
    document.getElementById(AppStyleCollections.Wallpaper.CONTAINER)?.remove()
    logger.info(`[${this.name}] 移除背景图片`)
  }

  /**
   * 样式
   */
  styles(): string {
    return `
:root {
  --wallpaper-alpha: 0;
  --wallpaper-filter: 0;
}

#${AppStyleCollections.Wallpaper.CONTAINER} {
  position: fixed;                        /* 固定定位 */
  z-index: -1;                            /* 确保在内容下层 */;
  height: 100vh;                          /* 使用视口单位 */;
  width: 100vw;
  background-size: cover;                 /* 调整图片大小 */
  background-position: center;            /* 调整图片位置 */
  background-attachment: fixed;           /* 增强固定效果 */
  background-repeat: no-repeat;           /* 防止图片重复 */
  filter: blur(var(--wallpaper-filter));
  left: calc(var(--wallpaper-filter)*-2);
  right: calc(var(--wallpaper-filter)*-2);
  top: calc(var(--wallpaper-filter)*-2);
  transform: translateZ(0);              /* 创建独立的合成层，解决弹窗打开/关闭时的偏移问题 */
  /* 优化性能 */
  will-change: transform;                /* 提前告知浏览器可能的变化 */
  backface-visibility: hidden;
  background-color: inherit !important;
  
  &.wallpaper.ready {
    transition: background-image .3s,background-color .2s;
    will-change: background-image;
  }
  
  .${AppStyleCollections.Wallpaper.MASK} {
    height: 100%;
    background-color: transparent !important;
  }
}

${BODY_SELECTOR}.${AppStyleCollections.Wallpaper.EXISTS} {
  background-color: transparent !important;

  #${AppStyleCollections.Wallpaper.CONTAINER} {
    background-color: transparent !important;
  }
}
`
  }
}
